from typing import Generator

from fastapi import Depends, HTTPException, status, Request
from fastapi.security import OAuth2PasswordBearer
from jose import jwt
from pydantic import ValidationError
from sqlalchemy.orm import Session

from app import services, models, schemas
from app.core import security
from app.core.config import settings
from app.db.session import SessionLocal
from app.core.exceptions import UnicornException
from app.schemas.base import BaseHeader
from datetime import datetime

reusable_oauth2 = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_STR}/login/access-token")


def get_db() -> Generator:
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()


def get_current_user(
        db: Session = Depends(get_db), token: str = Depends(reusable_oauth2)
) -> models.User:
    try:
        payload = jwt.decode(
            token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
        )
        token_data = schemas.TokenPayload(**payload)
    except (jwt.JWTError, ValidationError):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Could not validate credentials",
        )
    user = services.user.get(db, id=token_data.sub)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user


def get_current_active_user(
        current_user: models.User = Depends(get_current_user),
) -> models.User:
    if not services.user.is_active(current_user):
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user


def get_current_active_superuser(
        current_user: models.User = Depends(get_current_user),
) -> models.User:
    if not services.user.is_superuser(current_user):
        raise HTTPException(
            status_code=400, detail="The user doesn't have enough privileges"
        )
    return current_user

from jose import jwt, JWTError
from app.core.config import settings
from fastapi.responses import JSONResponse
from jose import jwt


# async def verify_weichat(request: Request,OpenId: str = Header(),db: Session = Depends(get_db)):
#     if OpenId:
#         args = ListFilterSchema(key="open_id",condition="=",value=OpenId)
#         obj = services.user.query_by_key(db,[args,])
#         if obj:
#             request.state.user = obj.id
#         else:
#             if request.url.path!='/api/v1/login':
#                 raise UnicornException(name="open_id错误")
#     else:
#         if request.url.path=='/api/v1/login':
#             pass
#         else:
#             raise UnicornException(name="open_id错误")


async def authorization(request: Request):
    if 'Authorization' in request.headers:
        token = request.headers.get('Authorization')
        try:
            payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
            request.state.user = payload.get("id")
        except JWTError:
            request.state.user=1
            #         raise UnicornException(name="Invalid authentication credentials")
    else:
        request.state.user = 1
        # raise UnicornException(name="authentication can not be null")

async def get_headers(request: Request):
    currency = request.headers.get("currency","USD").lower()
    lang = request.headers.get("lang","cn").lower()
    device = request.headers.get("device","pc").lower()
    return BaseHeader(currency=currency,lang=lang,device=device)

